About 10030 letters

About 50 minutes

#Using Qt in Python

Qt is a cross-platform graphical user interface framework. The current main versions are Qt5 and Qt6, with Qt5 no longer maintained.

In Python, there are two Qt6 packages: PyQt6 (third-party) and PySide6 (official Qt release). Their usage is almost identical.

#Installation

Install PySide6 with the following command:

pip install PySide6

#Basic Example

The following code creates a simple GUI program with a label and a button. Each time the button is clicked, the number on the label increases by one.

Qt Basic Example

import sys from PySide6.QtWidgets import ( QApplication, QMainWindow, QWidget, QLabel, QPushButton, QVBoxLayout, ) class Widget(QWidget): ''' Widget serves as the central widget of the window ''' def __init__(self): ''' Constructor ''' # Call superclass constructor super().__init__() # Counter variable self.__count = 0 # Create a label to display text self.__label = QLabel(f"Count: {self.__count}") # Create a button for clicking self.__button = QPushButton("Click Me") # Connect signal: when button clicked, call self.increase self.__button.clicked.connect(self.increase) # Create layout self.__layout = QVBoxLayout() self.__layout.addWidget(self.__label) self.__layout.addWidget(self.__button) self.setLayout(self.__layout) def increase(self): ''' Increase increments count and updates label ''' self.__count += 1 self.__label.setText(f"Count: {self.__count}") if __name__ == "__main__": app = QApplication(sys.argv) # Create application window = QMainWindow() # Create main window widget = Widget() # Create widget window.setCentralWidget(widget) # Set central widget window.show() # Show window app.exec() # Run program, returns when window closes

#Qt Main Window Layout

QMainWindow provides a basic framework for building application user interfaces:

Main Window Layout

  • Menu Bar — menu bar
  • Toolbars — toolbars, can have multiple
  • Dock Widgets — dockable widgets attached to the window edges, resizable and movable, can have multiple
  • Central Widget — the central widget responsible for the main functionality of the window
  • Status Bar — status bar, used to display status information

#Qt Layout System

Every Qt widget can have its own layout. Common layouts include horizontal layout (QHBoxLayout), vertical layout (QVBoxLayout), and grid layout (QGridLayout).

Layouts

import sys from PySide6.QtWidgets import ( QApplication, QMainWindow, QWidget, QPushButton, QVBoxLayout, QHBoxLayout, QGridLayout ) class Widget(QWidget): ''' Widget serves as the central widget of the window ''' def __init__(self): ''' Constructor ''' super().__init__() # Horizontal layout example self.__hbox = QHBoxLayout() self.__hbox.addWidget(QPushButton("hbox 1")) self.__hbox.addWidget(QPushButton("hbox 2")) self.__hbox.addWidget(QPushButton("hbox 3")) # Vertical layout example self.__vbox = QVBoxLayout() self.__vbox.addWidget(QPushButton("vbox 1")) self.__vbox.addWidget(QPushButton("vbox 2")) self.__vbox.addWidget(QPushButton("vbox 3")) # Grid layout example self.__grid = QGridLayout() self.__grid.addWidget(QPushButton("grid 1"), 0, 0) self.__grid.addWidget(QPushButton("grid 2"), 0, 1) self.__grid.addWidget(QPushButton("grid 3"), 1, 0) self.__grid.addWidget(QPushButton("grid 4"), 1, 1) # Layouts can contain layouts self.__main_layout = QVBoxLayout() self.__main_layout.addLayout(self.__hbox) self.__main_layout.addLayout(self.__vbox) self.__main_layout.addLayout(self.__grid) self.setLayout(self.__main_layout) if __name__ == "__main__": app = QApplication(sys.argv) # Create application window = QMainWindow() # Create main window widget = Widget() # Create widget window.setCentralWidget(widget) # Set central widget window.show() # Show window app.exec() # Run program, returns when window closes

#Qt Signals and Slots

Qt’s Signal & Slot mechanism is one of the core features of the Qt framework. It enables communication between objects, similar to event listeners but more powerful, flexible, and safe than traditional callbacks.

Usage: when a signal is emitted, the connected slot is called.

# Connect signal and slot object.signal.connect(slot) # Disconnect signal and slot object.signal.disconnect(slot) # Emit signal object.signal.emit()

To define a custom signal, the class must inherit from QObject. The signal is created as a class attribute:

class Widget(QWidget): # QWidget inherits from QObject, so no need to inherit QObject again my_signal = Signal() # Create signal

#Qt Styling

Qt uses QSS (similar to CSS) for styling. Widgets call setStyleSheet with a QSS string to set styles.

The style structure is as follows:

selector { property: value; property: value; property: value; }
  • Selector determines which widgets are affected, e.g., QLabel, QPushButton.
  • Properties and values specify styles, e.g., background-color: red sets the background to red.

Adding styles to the basic example code:

Layout

def __init__(self): # ... omitted for brevity # Set stylesheet self.setStyleSheet('''QWidget { background-color: #2b2b2b; color: #eeeeee; font-size: 16px; font-family: "Microsoft YaHei"; } QLabel { font-weight: bold; padding: 5px; color: #f0f0a0; } QPushButton { background-color: #3c3f41; border: 1px solid #555; border-radius: 5px; padding: 8px 16px; color: #ffffff; } QPushButton:hover { background-color: #505354; } QPushButton:pressed { background-color: #2c2f30; } ''')

Common properties:

CategoryProperty NameExample ValueDescription
Fontfont-size16pxFont size
font-family"Microsoft YaHei"Font family
font-weightnormal, bold, 100~900Font weight
font-stylenormal, italicFont style
color#ffffffFont color
Backgroundbackground-color#2b2b2b, transparentBackground color
background-imageurl(:/images/bg.png)Background image
background-repeatno-repeat, repeat-xBackground repeat mode
background-positioncenter, top leftBackground position
Borderborder1px solid #cccBorder style
border-width1pxBorder width
border-stylesolid, dashed, noneBorder style
border-color#ff0000Border color
border-radius5pxBorder radius (rounded corners)
Padding & Marginpadding5pxPadding (inner spacing)
margin5pxMargin (outer spacing)
Sizemin-width100pxMinimum width
max-height50pxMaximum height
width200pxFixed width
height200pxFixed height

Created in 5/15/2025

Updated in 5/21/2025